package com.example.aihub.controller;

import com.example.aihub.dto.CommentDTO;
import com.example.aihub.dto.UserDTO;
import com.example.aihub.entity.Comment;
import com.example.aihub.entity.Post;
import com.example.aihub.entity.User;
import com.example.aihub.service.CommentService;
import com.example.aihub.service.PostService;
import com.example.aihub.service.UserService;
import com.example.aihub.exception.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 评论控制器
 * 处理评论相关的HTTP请求，包括创建、回复、查询、更新和删除评论
 */
@RestController
@RequestMapping("/api/comments")
public class CommentController {

    private final CommentService commentService;
    private final PostService postService;
    private final UserService userService;

    /**
     * 构造函数
     * @param commentService 评论服务
     * @param postService 帖子服务
     * @param userService 用户服务
     */
    @Autowired
    public CommentController(CommentService commentService, PostService postService, UserService userService) {
        this.commentService = commentService;
        this.postService = postService;
        this.userService = userService;
    }

    /**
     * 创建评论
     * @param postId 帖子ID
     * @param commentDTO 评论DTO
     * @return 创建的评论DTO
     */
    @PostMapping("/posts/{postId}")
    public ResponseEntity<CommentDTO> createComment(@PathVariable Long postId, @RequestBody CommentDTO commentDTO) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + username));

        // 查找帖子
        Post post = postService.getPostById(postId)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在: " + postId));

        // 创建评论实体
        Comment comment = new Comment();
        comment.setContent(commentDTO.getContent());
        comment.setUser(user);
        comment.setPost(post);

        // 保存评论
        Comment savedComment = commentService.createComment(comment);

        // 转换为DTO
        CommentDTO responseDTO = convertToDTO(savedComment);

        return new ResponseEntity<>(responseDTO, HttpStatus.CREATED);
    }

    /**
     * 回复评论
     * @param commentId 被回复的评论ID
     * @param commentDTO 回复DTO
     * @return 回复的评论DTO
     */
    @PostMapping("/reply/{commentId}")
    public ResponseEntity<CommentDTO> replyToComment(@PathVariable Long commentId, @RequestBody CommentDTO commentDTO) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + username));

        // 创建回复实体
        Comment reply = new Comment();
        reply.setContent(commentDTO.getContent());
        reply.setUser(user);

        // 保存回复
        Comment savedReply = commentService.replyToComment(commentId, reply);

        // 转换为DTO
        CommentDTO responseDTO = convertToDTO(savedReply);

        return new ResponseEntity<>(responseDTO, HttpStatus.CREATED);
    }

    /**
     * 获取帖子的所有评论
     * @param postId 帖子ID
     * @return 评论DTO列表
     */
    @GetMapping("/posts/{postId}")
    public ResponseEntity<List<CommentDTO>> getCommentsByPostId(@PathVariable Long postId) {
        // 验证帖子是否存在
        postService.getPostById(postId)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在: " + postId));

        // 获取评论列表
        List<Comment> comments = commentService.getCommentsByPostId(postId);

        // 转换为DTO列表
        List<CommentDTO> commentDTOs = comments.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());

        return ResponseEntity.ok(commentDTOs);
    }

    /**
     * 更新评论
     * @param id 评论ID
     * @param commentDTO 包含更新信息的评论DTO
     * @return 更新后的评论DTO
     */
    @PutMapping("/{id}")
    public ResponseEntity<CommentDTO> updateComment(@PathVariable Long id, @RequestBody CommentDTO commentDTO) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + username));

        // 查找评论
        Optional<Comment> commentOptional = commentService.getCommentById(id);
        if (commentOptional.isEmpty()) {
            throw new ResourceNotFoundException("评论不存在: " + id);
        }

        Comment comment = commentOptional.get();

        // 检查权限
        if (!comment.getUser().getId().equals(user.getId())) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }

        // 更新评论内容
        comment.setContent(commentDTO.getContent());

        // 保存更新后的评论
        Comment updatedComment = commentService.updateComment(comment);

        // 转换为DTO
        CommentDTO responseDTO = convertToDTO(updatedComment);

        return ResponseEntity.ok(responseDTO);
    }

    /**
     * 删除评论
     * @param id 评论ID
     * @return 无内容响应
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteComment(@PathVariable Long id) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + username));

        // 查找评论
        Optional<Comment> commentOptional = commentService.getCommentById(id);
        if (commentOptional.isEmpty()) {
            throw new ResourceNotFoundException("评论不存在: " + id);
        }

        Comment comment = commentOptional.get();

        // 检查权限
        if (!comment.getUser().getId().equals(user.getId()) && !comment.getPost().getUser().getId().equals(user.getId())) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }

        // 删除评论
        commentService.deleteComment(id);

        return ResponseEntity.noContent().build();
    }

    /**
     * 将Comment实体转换为CommentDTO
     * @param comment 评论实体
     * @return 评论DTO
     */
    private CommentDTO convertToDTO(Comment comment) {
        CommentDTO dto = new CommentDTO();
        dto.setId(comment.getId());
        dto.setContent(comment.getContent());
        dto.setCreatedAt(comment.getCreatedAt());
        dto.setPostId(comment.getPost().getId());

        // 设置用户信息
        UserDTO userDTO = new UserDTO();
        userDTO.setId(comment.getUser().getId());
        userDTO.setUsername(comment.getUser().getUsername());
        dto.setUser(userDTO);

        // 设置父评论ID（如果有）
        if (comment.getParentComment() != null) {
            dto.setParentCommentId(comment.getParentComment().getId());
        }

        return dto;
    }
}